<template>
	<div class="conMain">
		<el-card class="box-card">
			<div slot="header" class="topfix">
				<el-form :inline="true" :model="params" size="small" class="goodsForm" label-width="100px">
					<el-form-item label="ID">
						<el-input clearable v-model="params.s_id" placeholder="请输入ID" />
					</el-form-item>
					<el-form-item label="账号">
						<el-input clearable v-model="params.s_username" placeholder="请输入账号" />
					</el-form-item>
					<el-form-item label="名称">
						<el-input clearable v-model="params.s_name" placeholder="请输入代理姓名" />
					</el-form-item>
					<el-form-item label="级别">
						<el-select clearable v-model="params.s_level" placeholder="请选择">
							<el-option :label="item.txt" :value="item.val" v-for="(item,index) in levellist" />
						</el-select>
					</el-form-item>
					<el-form-item label="状态">
						<el-select clearable v-model="params.s_status" placeholder="请选择">
							<el-option :label="item.txt" :value="item.val" v-for="(item,index) in statuslist" />
						</el-select>
					</el-form-item>
					<el-form-item label="模板">
						<el-select clearable v-model="params.s_goods_mb" placeholder="请选择">
							<el-option label="是" value="1" />
							<el-option label="否" value="0" />
						</el-select>
					</el-form-item>
					<el-form-item label="创建时间" prop="s_createtime">
						<el-date-picker v-model="params.s_createtime" type="daterange" value-format="yyyy-MM-dd"
							range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" />
					</el-form-item>
					<el-form-item label=" ">
						<el-button type="primary" size="small" class="searchBtn" @click="handleSearch"
							icon='el-icon-search'>搜索</el-button>
					</el-form-item>
				</el-form>
				<!-- <div style="text-align: right;" v-if="role != 3"> -->
				<div style="text-align: right;">
					<el-button v-has="'agent/agent/add'" type="primary" size="small" class="ml10" @click="add" plain><i class="el-icon-plus" /> 添加代理</el-button>
					<el-button type="primary" size="small" plain @click="copy()">邀请连接</el-button>
					<el-button type="success" size="small" plain  @click="qrcode()">邀请海报</el-button>
					<!-- <el-button   v-has="'agent/agent/export'"  type="warning" size="small" class="ml10" @click="down" plain><i class="el-icon-download" /> 导出</el-button> -->
				</div>

			</div>
			<el-table v-loading="loading" :data="list" style="width: 100%" :empty-text='emtypetxt'>
				<el-table-column prop="id" label="ID" align="center" width="100" />
				<el-table-column prop="username" label="登录账号" :show-overflow-tooltip="true" align="center"
					min-width="150" />
				<el-table-column prop="name" label="代理姓名" align="center" />
				<el-table-column prop="type" label="级别" align="center">
					<template slot-scope="scope">
						<span v-if="scope.row.level === 1">一级</span>
						<span v-else-if="scope.row.level === 2">二级</span>
						<span v-else-if="scope.row.level === 3">三级</span>
					</template>
				</el-table-column>
				<el-table-column prop="money" label="余额" align="center" min-width="80" v-if="role != 3" />
				<el-table-column prop="mobile" label="联系电话" align="center" />
				<el-table-column prop="xjnum" label="代理数量" align="center">
					<template slot-scope="scope">
						<span @click="xiaji(scope.row)">{{scope.row.xjnum}}</span>
					</template>
				</el-table-column>
				<el-table-column prop="sj" label="上级代理" align="center" />
				<el-table-column label="状态" align="center">
					<template slot-scope="scope">
						<el-tag v-if="scope.row.status == 1" type="info" size="mini" disable-transitions>待审核</el-tag>
						<el-tag v-else-if="scope.row.status == 2" type="success" size="mini"
							disable-transitions>正常</el-tag>
						<el-tag v-else-if="scope.row.status == -1" type="danger" size="mini"
							disable-transitions>禁用</el-tag>
					</template>
				</el-table-column>
				<el-table-column label="模板" align="center">
					<template slot-scope="scope">

						<el-tag v-if="scope.row.goods_mb == '1'" type="success" size="mini"
							disable-transitions>是</el-tag>
						<el-tag v-else-if="scope.row.goods_mb == '0'" type="danger" size="mini"
							disable-transitions>否</el-tag>
					</template>
				</el-table-column>
				<el-table-column label="标签" align="center">
					<template slot-scope="scope">
						<div v-for="(item,index) in lableList">
							<el-tag v-if="scope.row.lables.indexOf(item.val)!='-1'" type="success" size="mini" disable-transitions :style="{backgroundColor: item.colour,color:'#fff'}">{{item.txt}}</el-tag>
						</div>
					</template>
				</el-table-column>
				<el-table-column prop="createtime" label="创建时间" align="center" width="200" />
				<el-table-column label="操作" fixed="right" align="left" width="200">
					<template slot-scope="scope">
						<el-link v-if="role != 3" v-has="'agent/agent/edit'" :underline="false" type="primary"
							title='编辑' @click="edit(scope.row)">编辑</el-link>
						<el-link class="ml10" v-has="'agent/agent/reset'" :underline="false" type="warning" title='重置佣金'
							@click="reset(scope.row)">佣金</el-link>
              <el-link v-has="'agent/agent/recharge'" class="ml10" :underline="false" type="warning" title="余额充值"
              	@click="recharge(scope.row)">充值</el-link>
						<el-link v-if="scope.row.level<3" class="ml10" v-has="'agent/relation/index'" :underline="false"
							title='下级分销列表' @click="xiaji(scope.row)">分销</el-link>
						<el-link class="ml10" v-has="'agent/agent/edit'" :underline="false" type="primary" title='同步'
							@click="synchronizations(scope.row)">同步</el-link>
						<!-- <el-link class="ml10" v-has="'agent/agent/edit'" :underline="false" type="primary" title='佣金模板设置' @click="muban(scope.row.id)">模板</el-link> -->

					</template>
				</el-table-column>
			</el-table>
			<div class="pagination">
				<el-pagination :current-page="params.page" :page-sizes="[10, 20, 50, 100]" :page-size="params.pagesize"
					layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
					@current-change="handleCurrentChange" />
			</div>
		</el-card>
		<el-dialog :title="sub.id==0?'添加一级代理':'编辑代理'" :visible.sync="dialogVisible" :close-on-click-modal="false" center
			width="40%">
			<el-form ref="ruleForm" :model="sub" :rules="rules" label-width="110px">
				<el-form-item label="登录账号" prop="username">
					<el-input v-model="sub.username" :disabled="sub.id>0?true:false" clearable placeholder="请输入登录账号" />
				</el-form-item>
				<el-form-item label="登录密码" prop="password">
					<el-input :placeholder="sub.id==''?'为空则默认123456':'为空则不修改'" v-model="sub.password"
						show-password></el-input>
				</el-form-item>
				<el-row>
					<el-col :span="12">
						<el-form-item label="姓名称呼" prop="name">
							<el-input v-model="sub.name" clearable placeholder="请输入姓名或称呼" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="联系电话">
							<el-input v-model="sub.mobile" clearable placeholder="请输入手机号" />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row v-if="sub.id>0">
					<el-col :span="12">
						<el-form-item label="级别">
							<el-select v-model="sub.level" placeholder="请选择">
								<el-option disabled :label="item.txt" :value="item.val"
									v-for="(item,index) in levellist" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="可提余额">
							<el-input disabled v-model="sub.money" placeholder="">
								<template slot="append">元</template>
							</el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-form-item label="代理备注" prop="content">
					<el-input type="textarea" v-model="sub.content" placeholder="请输入代理备注"></el-input>
				</el-form-item>
				<el-form-item label="所属管理员" prop="pass_id">
					<el-select :disabled="sub.level==1?false:true" style="width:100%" filterable clearable
						v-model="sub.admin_id" placeholder="请选择">
						<el-option :label="item.name" :value="item.id" v-for="(item,index) in adminlist" />
					</el-select>
				</el-form-item>
				<el-form-item label="标签">
					<el-select  style="width:100%" multiple clearable
						v-model="sub.lables" placeholder="请选择">
						<el-option :label="item.txt" :value="item.val" v-for="(item,index) in lableList" />
					</el-select>
				</el-form-item>
				<!-- <el-form-item label="所属员工">
            <el-select :disabled="sub.level==1?false:true"  style="width:100%"  filterable clearable v-model="sub.staff_id"  placeholder="请选择">
                <el-option   :label="item.name" :value="item.id" v-for="(item,index) in stlist" />
            </el-select>
        </el-form-item> -->
				<el-form-item label="状态" prop="status">
					<el-radio-group v-model="sub.status">
						<el-radio :label="item.val" v-for="(item,index) in statuslist">{{item.txt}}</el-radio>
					</el-radio-group>
				</el-form-item>

				<el-form-item label="模板" prop="goods_mb">
					<el-radio-group v-model="sub.goods_mb">
						<el-radio label="1">是</el-radio>
						<el-radio label="0">否</el-radio>
					</el-radio-group>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="dialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="subForm('ruleForm')">确定</el-button>
			</div>
		</el-dialog>
		<el-dialog title="选择同步模板" :visible.sync="synchronization" :close-on-click-modal="false" center width="40%">
			<el-form>
				<el-form-item label="">
					<el-select style="width:100%" filterable clearable v-model="synitem.syncid" placeholder="请选择">
						<el-option :label="key+'-'+item" :value="key" v-for="(item,key) in synlist" />
					</el-select>
				</el-form-item>


			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="abolist">取 消</el-button>
				<el-button type="primary" @click="syn_ok()">确定</el-button>
			</div>
		</el-dialog>
		<el-dialog title="下级分销代理" :visible.sync="xjlistshow" :close-on-click-modal="false" left width="60%">

			<el-form v-if="boxxj" style="margin-top: 10px;" :inline="true" :model="paramsxj" size="small"
				label-width="100px">
				<el-form-item label="名称">
					<el-input clearable v-model="paramsxj['s_agent*name']" placeholder="请输入代理姓名" />
				</el-form-item>
				<el-form-item label="级别">
					<el-select filterable clearable v-model="paramsxj['s_agent*level']" placeholder="请选择">
						<el-option :label="item.txt" :value="item.val" v-for="(item,index) in levellistxj" />
					</el-select>
				</el-form-item>
				<el-form-item label=" ">
					<el-button type="primary" size="small" class="searchBtn" @click="handleSearchxj"
						icon='el-icon-search'>搜索</el-button>
				</el-form-item>
			</el-form>
			<div style="text-align: right;">
				<el-button icon="el-icon-search" type="info" plain size="small" @click="changeboxxj"></el-button>
			</div>

			<el-table v-loading="loadingxj" :data="xjlist" style="width: 100%" :empty-text='emtypetxtxj'>
				<el-table-column prop="agid" label="代理ID" align="center" width="100" />
				<el-table-column prop="agent.username" label="登录账号" :show-overflow-tooltip="true" align="center"
					min-width="150" />
				<el-table-column prop="agent.name" label="代理姓名" align="center" />
				<el-table-column prop="type" label="级别" align="center">
					<template slot-scope="scope">
						<span v-if="scope.row.agent.level === 1">一级</span>
						<span v-else-if="scope.row.agent.level === 2">二级</span>
						<span v-else-if="scope.row.agent.level === 3">三级</span>
					</template>
				</el-table-column>
				<el-table-column prop="agent.money" label="余额" align="center" min-width="80" v-if="role != 3" />
				<el-table-column prop="agent.mobile" label="联系电话" align="center" />
				<el-table-column prop="createtime" label="创建时间" align="center" width="200" />

			</el-table>
			<div class="pagination">
				<el-pagination :current-page="paramsxj.page" :page-sizes="[10, 20, 50, 100]"
					:page-size="paramsxj.pagesize" layout="total, prev, pager, next" :total="xjtotal"
					@current-change="handleCurrentChangexj" />
			</div>
		</el-dialog>

    <!-- 余额充值 start-->
    <el-dialog :title="'余额充值'" :visible.sync="rechargeVisible" :close-on-click-modal="false" center width="480px">
    	<el-form ref="ruleForm" :model="sub" :rules="rules" label-width="110px">
    		<el-form-item label="充值 id:">
    			<label>{{ sub.id }}</label>
    		</el-form-item>
    		<el-form-item label="充值账号:">
    			<label>{{ sub.username }}</label>
    		</el-form-item>
    		<el-form-item label="充值金额" prop="money">
    			<el-input v-model.number="sub.money" :placeholder="'减少金额可以输入负数'" type="number" />
    		</el-form-item>
			<el-form-item label="备注">
    			<el-input v-model="sub.msg" />
    		</el-form-item>
    	</el-form>
    	<div slot="footer" class="dialog-footer">
    		<el-button @click="rechargeVisible = false">取 消</el-button>
    		<el-button type="primary" @click="subFormRecharge('ruleForm')">确定</el-button>
    	</div>
    </el-dialog>
    <!-- 余额充值 end-->

		<el-dialog title="邀请海报" :visible.sync="hbVisible" :close-on-click-modal="false" left  width="60%">
				<div style="color:#686868;margin-bottom: 10px;">
				{{copyurl}}
				</div>
				<div style="text-align: center;">
				<el-image
					:src="qrcodeurl">
				</el-image>
				<div style="color:#686868">
					{{qrtitle}}
				</div>
				</div>
		</el-dialog>
	</div>
</template>

<script>
	import {
		agent_index,
		agent_add_post,
		agent_edit_post,
    agent_recharge_post,
		agent_reset,
		relation_index,
		agent_intive,
		agent_export,
		agent_fee_muban,
		agent_goodsMbLis,
		agent_goodssync,
		lable_list
	} from '@/api/agent'
	import {
		staff_list
	} from '@/api/staff'
	import {
		admin_list
	} from '@/api/admin'

	export default {
		data() {
			return {
				qrtitle: '',
				synlist: {},
				synchronization: false,
				synitem: {
					id: '',
					syncid: '',
				},
				total: 0,
				loading: true,
				role: 3,
				aid: '',
				emtypetxt: '',
				list: [],
				levellistxj: [{
					val: '2',
					txt: '二级'
				}, {
					val: '3',
					txt: '三级'
				}],
				levellist: [{
					val: '1',
					txt: '一级'
				}, {
					val: '2',
					txt: '二级'
				}, {
					val: '3',
					txt: '三级'
				}],
				statuslist: [{
					val: '1',
					txt: '待审核'
				}, {
					val: '2',
					txt: '正常'
				}, {
					val: '-1',
					txt: '禁用'
				}],
				params: {
					s_id: '',
					s_username: '',
					s_name: '',
					s_pass_id: '',
					s_status: '',
					s_createtime: [],
					ss_name: 'like',
					ss_createtime: 'BETWEEN',
					page: 1,
					pagesize: 10,
				},
        		rechargeVisible: false,
				dialogVisible: false,
				sub: {
					id: '',
					username: '',
					name: '',
					mobile: '',
					password: '',
					content: '',
					staff_id: '',
					lables: '',
					status: '1',
					goods_mb: '1'
				},
				hbVisible: false,
				copyurl: '',
				qrcodeurl: '',
				rules: {
					username: [{
							required: true,
							message: '登录账号不能为空',
							trigger: 'blur'
						},
						{
							min: 3,
							max: 20,
							message: '长度在 3 到 30 个字符',
							trigger: 'blur'
						}
					],
					name: [{
						required: true,
						message: '姓名称呼不能为空',
						trigger: 'blur'
					}, ],

				},
				xjlistshow: false,
				xjlist: [],
				xjtotal: 0,
				loadingxj: true,
				emtypetxtxj: '',
				paramsxj: {
					s_pid: '',
					's_agent*name': '',
					's_agent*level': '',
					page: 1,
					pagesize: 10,
				},
				boxxj: false,
				stlist: [], //所有员工
				adminlist: [], //所有员工
				lableList: '',

			}
		},
		created() {
			this.getList()
			lable_list().then(res => {
				this.lableList = res.data
			})
		},
		methods: {
			copy(){
				let url =  window.location.origin + '/hk/pages/login/register?type=2&code=' + this.aid;
			    //新建一个文本框
				let oInput = document.createElement('input');
				//赋值给文本框
				oInput.value = url;
				document.body.appendChild(oInput);
				// 选择对象;
				oInput.select();
				// 执行浏览器复制命令
				document.execCommand("Copy");
				//复制完成删除掉输入框
				oInput.remove()
				this.$notify({
					title:'邀请链接已复制',
					message:url,
					type: 'success',
					duration: 2000
				})
			},
			qrcode(){
				agent_intive([]).then(res => {
					this.hbVisible=true
					this.qrcodeurl=res.data.hb
				})
			},
			abolist() {
				this.synchronization = false
				this.synitem.id = ''
				this.synitem.syncid = ''
			},
			syn_ok() {
				agent_goodssync(this.synitem).then(res => {
					this.synchronization = false
					this.synitem.id = ''
					this.synitem.syncid = ''
				})

			},
			synchronizations(e) {
				this.synchronization = true
				this.synitem.id = e.id
				agent_goodsMbLis().then(res => {
					this.synlist = res.msg
				})
			},
			getList() {
				this.emtypetxt = '加载中...';
				this.loading = true;
				agent_index(this.params).then(res => {
					this.list = res.data.list
					this.total = res.data.total
					this.role = res.data.role
					this.aid = res.data.id
					this.loading = false
					if (this.list.length == 0) {
						this.emtypetxt = '暂无数据'
					}
				})
			},

			handleSearch() {
				this.list = [];
				this.params.page = 1;
				this.getList()
			},
			//分页
			handleSizeChange(val) {
				this.params.pagesize = val
				this.getList()
			},
			handleCurrentChange(val) {
				this.params.page = val
				this.getList()
			},
			add() {
				staff_list({
					status: 1
				}).then(res => {
					this.stlist = res.data
				})
				admin_list({
					status: 1
				}).then(res => {
					this.adminlist = res.data
				})
				this.sub = {
					id: '',
					username: '',
					name: '',
					mobile: '',
					password: '',
					content: '',
					staff_id: '',
					admin_id: '',
					lables: '',
					status: '1',
					goods_mb: '1'
				}
				this.dialogVisible = true
			},
			edit(row) {
				// console.log(row,"12345");
				staff_list().then(res => {
					this.stlist = res.data
				})
				admin_list({
					status: 1
				}).then(res => {
					this.adminlist = res.data
				})
				if (row.lables.indexOf("[") != -1) {
					var labs = JSON.parse(row.lables)
				} else {
					var labs = row.lables
				}
				this.sub = {
					id: row.id,
					level: row.level + '',
					username: row.username,
					name: row.name,
					mobile: row.mobile,
					password: '',
					content: row.content,
					staff_id: '',
					admin_id: row.admin_id,
					status: row.status + '',
					lables: labs,
					money: row.money,
					goods_mb: row.goods_mb + ''
				}
				// console.log(this.sub,"oiuytrertyu");
				this.dialogVisible = true
			},
			subForm(formName) {
				this.$refs[formName].validate((valid) => {
					if (valid) {
						if (this.sub.id > 0) {
							agent_edit_post(this.sub).then(res => {
								this.$message.success(res.msg)
								this.dialogVisible = false
								this.getList()
							})
						} else {
							agent_add_post(this.sub).then(res => {
								this.$message.success(res.msg)
								this.dialogVisible = false
								this.getList()
							})
						}
					} else {
						return false;
					}
				});
			},
			reset(row) {
				this.$prompt('设置差价值，自动重置该分销商所有商品佣金', '差价重置佣金', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					inputPattern: /^[0-9]*$/,
					inputErrorMessage: '金额不正确'
				}).then(({
					value
				}) => {

					if (value == null || value < 0) {
						this.$message.error('金额不正确')
						return
					}
					agent_reset({
						id: row.id,
						fee: value
					}).then(res => {
						this.$message.success(res.msg)
						this.getList()
					})

				});
			},
			xiaji(row) {
				this.xjlistshow = true
				this.paramsxj.s_pid = row.id
				this.getXj()

			},
			getXj() {
				this.emtypetxtxj = '加载中...';
				this.loadingxj = true;
				relation_index(this.paramsxj).then(res => {
					this.xjlist = res.data.list
					this.xjtotal = res.data.total
					this.loadingxj = false
					if (this.xjlist.length == 0) {
						this.emtypetxtxj = '暂无数据'
					}
				})
			},
			handleCurrentChangexj(val) {
				this.paramsxj.page = val
				this.getXj()
			},
			changeboxxj() {
				this.boxxj = !this.boxxj;
			},
			handleSearchxj() {
				this.xjlist = [];
				this.paramsxj.page = 1;
				this.getXj()
			},
			down() {
				const loading = this.$loading({
					lock: true,
					text: '正在导出...',
					spinner: 'el-icon-loading',
					background: 'rgba(20, 20, 20, 0.7)'
				});
				agent_export(this.params).then(res => {
					const {
						export_json_to_excel
					} = require('../../assets/js/Export2Excel');
					const tHeader = res.data.header;
					const filterVal = res.data.filter;
					const list = res.data.list;
					const data = this.formatJson(filterVal, list);
					export_json_to_excel(tHeader, data, res.data.ename);
					loading.close();
				})
			},
			formatJson(filterVal, jsonData) {
				return jsonData.map(v => filterVal.map(j => v[j]))
			},
			muban(id) {
				this.$modalForm(agent_fee_muban({
					id: id
				})).then(() => this.getListmb())
			},
      recharge(row) {
				staff_list().then(res => {
					this.stlist = res.data
				})
				this.sub = {
					id: row.id,
					username: row.username,
					money: ''
				}
				this.rechargeVisible = true
			},
			subFormRecharge(formName) {
				this.$refs[formName].validate((valid) => {
					if (valid) {
						agent_recharge_post(this.sub).then(res => {
							this.$message.success(res.msg)
							this.rechargeVisible = false
							this.getList()
						})
					} else {
						return false
					}
				})
			},

		},
	}
</script>

<style lang="scss" scoped>


</style>
